Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
Combine property setter "init and private" (C#9)

I ask about the new C#9-feature "init property setter". Below an example of it:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init; }
}

My question is how I can update the value of 'Position' after initialize. I want something like this:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init + private set; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        Position = newPositionIndex;
    }
}

In my real world project an instance of MyClass is initialized by entity framework. Then I call some business methods on it. The rule is that only business methods are allowed to set values on properties, so I want at least private setters. But if I have private setters then entity framework cannot initialize the properties.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

It seems that this feature is not available for auto-properties in C#9.

To solve this issue I combine init with the full property style (instead auto property). Maybee C#10 or later would support such an access modifier.

public class MyClass
{
    private int _position;

    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get => _position; init => _position = value; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        _position = newPositionIndex;
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda